;;; texi-to-docstrings.scm --- Generate docstrings from a texi file

;; Copyright © 2016 Alex Kost <alezost@gmail.com>

;; This file is part of Guile-XOSD.

;; Guile-XOSD is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; Guile-XOSD is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with Guile-XOSD.  If not, see <http://www.gnu.org/licenses/>.

;;; Commentary:

;; Write to stdout the docstrings of Guile procedures, produced from a
;; texinfo file passed as argument.  The output has a form described by
;; the Guile Documentation Format version 2 - see the commentary in
;; (ice-9 documentation) module.

;; This script is based on "libguile/texi-fragments-to-docstrings" file
;; from the Guile source tree.

;;; Code:

(use-modules
 (ice-9 match)
 (ice-9 regex)
 (rnrs io ports)
 (texinfo)
 (texinfo plain-text))

(define deffn-regexp
  (make-regexp "^@deffn \\{Scheme Procedure\\} ([^ ]+)"
               regexp/newline))

(define (display-docstrings texi-str)
  (define texi->doc
    (compose stexi->plain-text texi-fragment->stexi))

  (define (display-doc head-match)
    (when head-match
      (let* ((proc-name  (match:substring head-match 1))
             (head-start (match:start     head-match))
             (head-end   (match:end       head-match))
             (next-match (regexp-exec deffn-regexp texi-str head-end))
             (doc-end    (if next-match
                             (match:start next-match)
                             (string-length texi-str))))
        (display #\page)
        (display proc-name)
        (newline)
        (newline)
        (display (texi->doc (substring texi-str head-start doc-end)))
        (display-doc next-match))))

  (display-doc (regexp-exec deffn-regexp texi-str)))

(match (command-line)
  ((me file)
   (format #t "Generated by '~a' from '~a'.~%~%"
           me file)
   (display-docstrings (call-with-input-file file get-string-all)))
  ((me _ ...)
   (format #t "Usage: guile ~a TEXI-FILE
Display docstrings of procedures from TEXI-FILE in the Guile
Documentation Format.\n"
           me)
   (exit 1)))

;;; texi-to-docstrings.scm ends here
